require 'osx/cocoa'
require 'macos/key_map'

class STGameController < OSX::NSObject
  attr_accessor :game
  attr_accessor :views
  attr_accessor :player
  attr_accessor :display_centers
  
  ib_outlet :throttle_meter
  ib_outlet :speedo
  
  def initialize
    @views = []
    @keys = {}
    123.upto(126) do |k|
      @keys[k] = false
    end
    @keys[KEY_SPACE] = false
    
    @game = Game.new
    @game.paused = false
    
    @player = GameObject.load("player")
    @player.position = Point.new(200, 200)
    
    @game.objects << @player
    
    1.upto(10) do |i|
      planet = GameObject.load("planet")
      planet.name = "Planet #{i}"
      planet.position = Point.new(rand(600), rand(200))
      @game.objects << planet
    end
  end
  
  def tick
    @player.throttle += 0.01 if keyPressed?(KEY_UP_ARROW) and @player.throttle < 1.0
    @player.throttle -= 0.01 if keyPressed?(KEY_DOWN_ARROW) and @player.throttle > 0.0
    
    @player.rotation_vector = -1 if keyPressed?(KEY_RIGHT_ARROW)
    @player.rotation_vector = 1 if keyPressed?(KEY_LEFT_ARROW)
    @player.rotation_vector = 0 unless keyPressed?(KEY_RIGHT_ARROW) or keyPressed?(KEY_LEFT_ARROW)
    
    if keyPressed?(KEY_SPACE)
      @player.speed = 0
      @player.throttle = 0.0
      @player.rotation_vector = 0
    end
    
    @game.update
    @views.each do |v|
      v.update
    end
    
    @speedo.setIntegerValue(@player.speed) unless @speedo.nil?
    @throttle_meter.setFloatValue(@player.throttle) unless @throttle_meter.nil?
  end
  
  ib_action :toggle_pause do |sender|
    @game.paused = !@game.paused?
    sender.state = @game.paused? ? NSOnState : NSOffState
  end
  
  ib_action :throttle_changed do |sender|
    @player.throttle = sender.floatValue
  end
  
  ib_action :display_center_changed do |sender|
    @display_centers = !@display_centers
    sender.state = @display_centers ? NSOnState : NSOffState
  end
  
  def keyDown(event)
    @keys[event.keyCode] = true unless @game.paused?
  end
  
  def keyUp(event)    
    @keys[event.keyCode] = false unless @game.paused?
  end
  
  def keyPressed?(keyCode)
    @keys[keyCode]
  end
  
  def displayCenterPoints?
    @display_centers
  end
end